package org.example.back.service.user;

import org.example.back.entity.user.UserMeal;
import org.example.back.entity.user.UserMealFood;
import org.example.back.mapper.user.UserMealMapper;
import org.example.back.service.advice.UserMealAdviceService;
import org.example.back.service.healthassistant.HealthAssistantService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
public class UserMealService {

    @Autowired
    private UserMealMapper userMealMapper;

    @Autowired
    private UserMealAdviceService userMealAdviceService;

    @Autowired
    private HealthAssistantService healthAssistantService;

    /**
     * 添加一条用餐记录及其食材信息，自动补全营养字段
     */
    @Transactional
    public void addUserMealWithFoods(UserMeal meal) {
        System.out.println("[UserMealService] 开始添加用餐记录");

        // 如果营养字段为空，调用大模型补全
        if (meal.getCalories() == null) {
            try {
                StringBuilder foodPrompt = new StringBuilder();
                if (meal.getFoods() != null && !meal.getFoods().isEmpty()) {
                    for (UserMealFood food : meal.getFoods()) {
                        foodPrompt.append(food.getName())
                                .append("，")
                                .append(food.getAmount())
                                .append("g；");
                    }
                }

                String prompt = String.format(
                        "请你估算以下食物的总热量和主要营养素，返回 JSON 格式：{\"calories\":..., \"carbohydrate\":..., \"protein\":..., \"fat\":..., \"fiber\":...}，食物列表：%s",
                        foodPrompt.toString()
                );

                System.out.println("[UserMealService] 调用大模型，prompt: " + prompt);

                String answer = healthAssistantService.getAnswerFromLLM(prompt);
                System.out.println("[UserMealService] 大模型返回结果: " + answer);

                Map<String, BigDecimal> nutrients = parseNutritionJson(answer);

                meal.setCalories(nutrients.getOrDefault("calories", BigDecimal.ZERO));
                meal.setCarbohydrate(nutrients.getOrDefault("carbohydrate", BigDecimal.ZERO));
                meal.setProtein(nutrients.getOrDefault("protein", BigDecimal.ZERO));
                meal.setFat(nutrients.getOrDefault("fat", BigDecimal.ZERO));
                meal.setFiber(nutrients.getOrDefault("fiber", BigDecimal.ZERO));
            } catch (Exception e) {
                System.err.println("[UserMealService] 调用大模型失败：" + e.getMessage());
                // 兜底设置为 0
                meal.setCalories(BigDecimal.ZERO);
                meal.setCarbohydrate(BigDecimal.ZERO);
                meal.setProtein(BigDecimal.ZERO);
                meal.setFat(BigDecimal.ZERO);
                meal.setFiber(BigDecimal.ZERO);
            }
        } else {
            System.out.println("[UserMealService] 营养字段已存在，不调用大模型");
        }

        // 插入主记录
        int insertCount = userMealMapper.insertUserMeal(meal);
        userMealAdviceService.cleanWeekAndMonthAdviceCache(meal.getUserId());
        System.out.println("[UserMealService] 插入主表记录数: " + insertCount + ", 生成ID: " + meal.getId());

        // 插入食材记录
        if (meal.getFoods() != null && !meal.getFoods().isEmpty()) {
            for (UserMealFood food : meal.getFoods()) {
                food.setUserMealId(meal.getId());
                System.out.println("[UserMealService] 插入子表记录，userMealId=" + food.getUserMealId()
                        + ", 食材名称=" + food.getName() + ", 数量=" + food.getAmount());
                int foodInsertCount = userMealMapper.insertUserMealFood(food);
                System.out.println("[UserMealService] 插入子表记录数: " + foodInsertCount);
            }
        } else {
            System.out.println("[UserMealService] 没有食材记录需要插入");
        }
    }

    /**
     * 查询某天所有用餐记录，带上对应的食材列表
     */
    public List<UserMeal> getMealsByDate(Integer userId, LocalDate date) {
        List<UserMeal> meals = userMealMapper.findMealsByDate(userId, date);
        if (meals != null && !meals.isEmpty()) {
            for (UserMeal meal : meals) {
                List<UserMealFood> foods = userMealMapper.findFoodsByUserMealId(meal.getId());
                meal.setFoods(foods);
            }
        }
        return meals;
    }
    //聚合查找某天的摄入量
    public Map<String, Object> getDailyNutritionPercentagesWithCalories(Integer userId, LocalDate date) {
    return userMealMapper.getDailyNutritionPercentagesWithCalories(userId, date);
}
    /**
     * 删除某天所有用餐记录及其对应的食材记录
     */
    @Transactional
    public void deleteUserMeal(Integer userId, LocalDate date) {
        List<UserMeal> meals = userMealMapper.findMealsByDate(userId, date);
        if (meals != null && !meals.isEmpty()) {
            for (UserMeal meal : meals) {
                userMealMapper.deleteUserMealFoodByMealId(meal.getId());
                System.out.println("[UserMealService] 删除子表用餐食材记录，userMealId=" + meal.getId());
            }
        }
        userMealMapper.deleteUserMeal(userId, date);
        System.out.println("[UserMealService] 删除主表用餐记录，userId=" + userId + ", date=" + date);
    }
    /**
     * 根据 userId、mealDate、mealTime 删除用餐及其所有食材明细
     */
    public boolean deleteMealByUserDateTime(Integer userId, LocalDate mealDate, String mealTime) {
        // 先查找对应用餐记录
        UserMeal meal = userMealMapper.findMealByUserDateTime(userId, mealDate, mealTime);
        if (meal == null) {
            return false; // 没有该记录
        }

        // 删除对应的食材明细
        userMealMapper.deleteUserMealFoodByMealId(meal.getId());

        // 删除用餐主表记录
        int rows = userMealMapper.deleteUserMealById(meal.getId());
        return rows > 0;
    }

    
    /**
     * 修改用餐记录（不含食材）
     */
    public void updateUserMeal(UserMeal meal) {
        int updateCount = userMealMapper.updateUserMeal(meal);
        System.out.println("[UserMealService] 修改用餐记录，更新条数=" + updateCount);
        userMealAdviceService.cleanWeekAndMonthAdviceCache(meal.getUserId());
    }

    /**
     * 获取过去7天的每日汇总数据
     */
    public List<Map<String, Object>> getLast7DaysSummary(Integer userId) {
        return userMealMapper.getLast7DaysSummary(userId);
    }

    /**
     * 获取过去30天的每周汇总数据
     */
    public List<Map<String, Object>> getLast30DaysSummary(Integer userId) {
        return userMealMapper.getUserMealLastMonthByWeek(userId);
    }

    /**
     * 简单解析大模型返回的 JSON（不使用第三方 JSON 库）
     */
    private Map<String, BigDecimal> parseNutritionJson(String json) {
        Pattern pattern = Pattern.compile("\"(calories|carbohydrate|protein|fat|fiber)\":\\s*(\\d+(\\.\\d+)?)");
        Matcher matcher = pattern.matcher(json);

        Map<String, BigDecimal> result = new java.util.HashMap<>();
        while (matcher.find()) {
            String key = matcher.group(1);
            BigDecimal value = new BigDecimal(matcher.group(2));
            result.put(key, value);
        }

        return result;
    }
}
